package pBonus_SEMAPHORES_from_jenkow;

import java.util.Date;
import java.util.concurrent.Semaphore;

public class SemaphoreTests {

  public static void main(String[] args) {
    Semaphore semaphore = new Semaphore(2);

    for (int i = 0; i < 10; i++) {
      new Worker(semaphore).start();
    }
  }
}

class Worker extends Thread {
  private Semaphore semaphore;

  public Worker(Semaphore semaphore) {
    this.semaphore = semaphore;
  }

  @Override
  public void run() {

    while (true) {
      try {
        semaphore.acquire();

        String msg = Thread.currentThread().getName() + " - running at: "
            + new Date();

        System.out.println(msg);

        Thread.sleep(5000);

      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        break;
      } finally {
        semaphore.release();
      }
    }
  }
}